package com.ygqh.baby.controller.mobile;

import com.ygqh.baby.ao.*;
import com.ygqh.baby.po.YgAgent;
import com.ygqh.baby.po.YgAgentInviteRecord;
import com.ygqh.baby.po.YgUser;
import com.ygqh.baby.service.*;
import com.ygqh.baby.service.impl.DocumentConstant;
import com.ygqh.baby.utils.DateConvertUtils;
import com.ygqh.baby.utils.SessionUtil;
import com.ygqh.baby.utils.ShareCodeUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Arrays;
import java.util.Date;

/**
 * 代理用户
 */
@Controller
@RequestMapping("/app/agent")
public class YgAgentController extends BaseController {

	protected final Logger logger = Logger.getLogger(this.getClass());

	@Autowired
	private YgAgentService ygAgentService;
	@Autowired
	private DocumentConstant documentConstant;
	@Autowired
	private YgAgentInviteRecordService ygAgentInviteRecordService;
	@Autowired
	private YgUserService ygUserService;
	@Autowired
	private WxSmallMessageService wxSmallMessageService;
	@Autowired
	private YgInformService ygInformService;

	/**
	 * 保存代理申请
	 *
	 * @return
	 */
	@RequestMapping(value = "saveAgent")
	@ResponseBody
	public ResponseEntity saveAgent(Long id, String trueName, String identityCard, String email, String address, String childAge, String fromChannel,
									String advantage, String suggest) {
		YgUser user = SessionUtil.getCurrentUser();
		YgAgent dbAgent = ygAgentService.findByRecent(user.getId(), UserType.UserAgent);
		if (dbAgent != null && !dbAgent.getCheckStatus().equals(CheckStatus.Reject)) {
			return ResponseEntity.error(documentConstant.SEND_COUNT_OVER, null);
		}
		YgAgent agent = new YgAgent();
		agent.setUserId(user.getId());
		/* agent.setId(id); */
		agent.setAddress(address);
		agent.setTrueName(trueName);
		agent.setTelPhone(user.getUserName());
		agent.setChildAge(childAge);
		agent.setEmail(email);
		agent.setFromChannel(fromChannel);
		agent.setIdentityCard(identityCard);
		agent.setAdvantage(advantage);
		agent.setCreateTime(new Date());
		agent.setSuggest(suggest);
		agent.setCheckBy(null);
		agent.setCheckTime(null);
		agent.setCheckStatus(CheckStatus.Waiting);
		ygAgentService.saveOrUpdate(agent);

		return ResponseEntity.success();
	}

	/**
	 * 根据用户获得代理信息
	 *
	 * @return
	 */
	@RequestMapping(value = "findAgent")
	@ResponseBody
	public ResponseEntity findAgent() {
		YgUser user = SessionUtil.getCurrentUser();
		YgAgentInviteRecord agent = ygAgentInviteRecordService.findRecordForYijiandian(user.getId());
		Message json = Message.success(documentConstant.MESSAGE_SUCCESS, agent);
		return ResponseEntity.converter(json);
	}

	/**
	 * 验证用户是否有请求代理资格
	 *
	 * @return
	 */
	@RequestMapping(value = "validateAgent")
	@ResponseBody
	public ResponseEntity validateAgent() {
		YgUser user = SessionUtil.getCurrentUser();
		boolean result = ygAgentService.validateAgentStatus(user.getId());
		return ResponseEntity.success(result);
	}

	/**
	 * 填写邀请码成为代理
	 *
	 * @param inviteCode
	 * @return
	 */
	@RequestMapping(value = "rechargeUserAgent")
	@ResponseBody
	public ResponseEntity rechargeUserAgent(@RequestParam String inviteCode) {
		Message message = ygAgentInviteRecordService.rechargeUserAgent(inviteCode, SessionUtil.getCurrentUser().getId());
		return ResponseEntity.converter(message);
	}

	/**
	 * 获取代理邀请码信息
	 *
	 * @param isReceive 是否已被领取
	 * @return
	 */
	@RequestMapping(value = "findInviteRecordByIsReceive")
	@ResponseBody
	public ResponseEntity findInviteRecordByIsReceive(Boolean isReceive) {
		Message message;
		Long userId = SessionUtil.getCurrentUser().getId();
		if (isReceive != null && isReceive) {
			message = Message.success(ygAgentInviteRecordService.findReceiveListByUserId(userId));
		} else {
			Date now = new Date();
			Date startDate = DateConvertUtils.getMonthStartDate(now);
			Date endDate = DateConvertUtils.getDateEnd(DateConvertUtils.getDateEnd(DateConvertUtils.getMonthEndDate(now)));
			message = Message.success(ygAgentInviteRecordService.findByUserIdListAndBetweenTime(Arrays.asList(userId), startDate, endDate));
		}
		return ResponseEntity.converter(message);
	}

	/**
	 * 立即成为新代理（只适用于原女王、原代理和待审核的代理）
	 *
	 * @return
	 */
	@RequestMapping(value = "rechargeUserAgentRightNow")
	@ResponseBody
	public ResponseEntity rechargeUserAgentRightNow() {
		Message message = ygAgentInviteRecordService.rechargeUserAgentRightNow(SessionUtil.getCurrentUser().getId(), Boolean.FALSE);
		return ResponseEntity.converter(message);
	}

	/**
	 * 邀请用户立即成为新代理 （只适用于普通用户）
	 *
	 * @return
	 */
	@RequestMapping(value = "rechargeUserAgentByInviteUser")
	@ResponseBody
	public ResponseEntity rechargeUserAgentByInviteUser() {
		Message message = ygAgentInviteRecordService.rechargeUserAgentRightNow(SessionUtil.getCurrentUser().getId(), Boolean.TRUE);
		return ResponseEntity.converter(message);
	}

	/**
	 * 成为代理（壹家店）
	 *
	 * @return
	 * @date 2019/04/08 10:58
	 * @version 2.0
	 */
	@RequestMapping(value = "rechargeUserAgent", params = {"version=2.0"})
	@ResponseBody
	public ResponseEntity rechargeUserAgent() {
		YgUser currentUser = SessionUtil.getCurrentUser();
		YgUser user = ygUserService.findById(currentUser.getId());
		if (UserType.UserAgent.equals(user.getUserType())) {
			currentUser.setUserType(UserType.UserAgent);
		} else {
			// 校验用户是否有成为会员的资格
			ResponseEntity response = ygAgentInviteRecordService.validateUserForUserAgent(user, PLATFORM_NO, SALES_PLATFORM);
			if (!response.isSuccess()) {
				return response;
			}
			ygAgentService.rechargeUserAgent(user, "rechargeUserAgentByCommon", PLATFORM_NO);
		}
		return ResponseEntity.success();
	}

	/**
	 * 填写邀请码绑定上级用户
	 *
	 * @param inviteCode
	 * @return
	 */
	@RequestMapping(value = "bindShareUser")
	@ResponseBody
	public ResponseEntity bindShareUser(@RequestParam String inviteCode) {
		YgUser currentUser = SessionUtil.getCurrentUser();
		YgAgentInviteRecord record = ygAgentInviteRecordService.findRecordForYijiandian(currentUser.getId());
		if (record != null) {
			return ResponseEntity.error("亲，您已有邀请用户，无需绑定", null);
		}
		long inviteUserId;
		try {
			inviteUserId = ShareCodeUtil.codeToId(inviteCode);
		} catch (Exception e) {
			e.printStackTrace();
			return ResponseEntity.error("亲，邀请码不存在，请输入正确邀请码", null);
		}
		if (currentUser.getId() == inviteUserId) {
			return ResponseEntity.error("亲，不能邀请自己哦", null);
		}
		YgUser inviteUser = ygUserService.findById(inviteUserId);
		if (inviteUser == null) {
			return ResponseEntity.error("亲，邀请码不存在，请输入正确邀请码", null);
		}
		record = ygAgentInviteRecordService.findRecordForYijiandian(inviteUserId);
		if (record != null && record.getUserId().compareTo(currentUser.getId()) == 0) {
			return ResponseEntity.error("亲，不可以绑定粉丝为邀请用户", null);
		}
		record = new YgAgentInviteRecord(null, currentUser.getId(), currentUser.getUserName(),
				new Date(), InviteType.Ordinary, CheckStatus.Pass, null);
		record.setUserId(inviteUser.getId());
		record.setUserName(inviteUser.getUserName());
		record.setCreateTime(new Date());
		record.setReceiveTime(record.getCreateTime());
		ygAgentInviteRecordService.save(record);

		ygInformService.asyncSendInform(inviteUser.getId(), currentUser.getNickName(),
				InformType.InviteSuccess, "inviteUser");
		return ResponseEntity.success(inviteCode);
	}
}
